package danran.dbapi.service;

import danran.dbapi.domain.Plugin;
import danran.dbapi.mapper.PluginMapper;
import danran.dbapi.plugin.loader.PluginClassLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Classname PluginService
 * @Description TODO
 * @Date 2022/2/9 15:56
 * @Created by RanCoder
 */
@Service
public class PluginService {
    @Autowired
    private PluginMapper pluginMapper;

    @Transactional
    public void addPlugin(Plugin plugin) {
        pluginMapper.insert(plugin);
    }

    @Transactional
    public void deletePlugin(int pluginId) {
        Plugin plugin = pluginMapper.selectById(pluginId);
        String[] files = plugin.getFiles().split(";");
        for (String file : files) {
            deleteFile(file);
        }
        pluginMapper.deleteById(pluginId);
    }

    public Plugin getPlugin(int id) {
        return pluginMapper.selectById(id);
    }

    public List<Plugin> getAllPlugins() {
        return pluginMapper.selectList(null);
    }

    private boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            return file.delete();
        }
        return true;
    }

    @Transactional
    public void addPluginInUse(String... pluginNames) {
        for (String pluginName : pluginNames) {
            addPluginInUseByName(pluginName);
        }
    }

    private void addPluginInUseByName(String pluginName) {
        pluginMapper.addInUse(pluginName);
    }

    @Transactional
    public void decrePluginInUse(String... pluginNames) {
        for (String pluginName : pluginNames) {
            decrePluginInUseByName(pluginName);
        }
    }

    private void decrePluginInUseByName(String pluginName) {
        pluginMapper.decreInUse(pluginName);
    }

    public Map<String, Integer> getPluginMapNameToId() {
        List<Plugin> plugins = pluginMapper.selectList(null);
        return plugins.stream().collect(Collectors.toMap(Plugin::getName, Plugin::getId));
    }
}
